<template>
  <div class="property-panel">
    <div class="panel-header">
      <h3>{{ selectedNode ? '节点配置' : '属性面板' }}</h3>
      <el-button
        v-if="selectedNode"
        size="small"
        type="danger"
        text
        @click="handleDeleteNode"
      >
        删除节点
      </el-button>
    </div>
    <div class="panel-body">
      <el-empty v-if="!selectedNode" description="请选择一个节点进行配置" />

      <div v-else class="node-config">
        <el-form :model="nodeConfig" label-width="100px" label-position="top">
          <!-- 节点基本信息 -->
          <el-form-item label="节点ID">
            <el-input :value="selectedNode.id" disabled />
          </el-form-item>

          <el-form-item label="节点类型">
            <el-input :value="nodeTypeLabel" disabled />
          </el-form-item>

          <el-form-item label="节点名称">
            <el-input v-model="nodeConfig.label" placeholder="请输入节点名称" />
          </el-form-item>

          <el-divider />

          <!-- 动态配置字段 -->
          <template v-for="field in configFields" :key="field.key">
            <!-- 输入框 -->
            <el-form-item
              v-if="field.type === 'input'"
              :label="field.label"
              :required="field.required"
            >
              <el-input
                v-model="nodeConfig.config[field.key]"
                :placeholder="field.placeholder"
              />
            </el-form-item>

            <!-- 下拉选择 -->
            <el-form-item
              v-else-if="field.type === 'select'"
              :label="field.label"
              :required="field.required"
            >
              <el-select
                v-model="nodeConfig.config[field.key]"
                :placeholder="field.placeholder"
                :loading="field.key === 'template_id' && templateStore.loading"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="option in getFieldOptions(field)"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <div v-if="field.key === 'template_id' && getFieldOptions(field).length === 0" class="field-hint">
                <el-text type="warning" size="small">暂无可用模板，请先创建实验模板</el-text>
              </div>
            </el-form-item>

            <!-- 实验配置编辑按钮（仅对 create_experiment 节点显示） -->
            <el-form-item
              v-if="field.key === 'template_id' && selectedNode.type === 'create_experiment'"
              label="实验配置"
            >
              <div class="config-editor-section">
                <el-button
                  type="primary"
                  @click="openConfigEditor"
                  :icon="Edit"
                  :disabled="!nodeConfig.config.template_id"
                >
                  编辑实验配置
                </el-button>
                <div v-if="nodeConfig.config.experimentConfig" class="config-status">
                  <el-tag type="success" size="small">已配置</el-tag>
                  <el-button
                    type="primary"
                    text
                    size="small"
                    @click="previewConfig"
                  >
                    预览
                  </el-button>
                </div>
                <el-text v-else type="info" size="small">
                  未配置，将使用模板默认配置
                </el-text>
              </div>
            </el-form-item>

            <!-- JSON编辑器 -->
            <el-form-item
              v-else-if="field.type === 'json'"
              :label="field.label"
              :required="field.required"
            >
              <el-input
                v-model="nodeConfig.config[field.key]"
                type="textarea"
                :rows="4"
                :placeholder="field.placeholder"
              />
            </el-form-item>

            <!-- 条件分支配置 -->
            <el-form-item
              v-else-if="field.type === 'conditions'"
              :label="field.label"
              :required="field.required"
            >
              <div class="conditions-config">
                <div
                  v-for="(condition, index) in nodeConfig.config.conditions"
                  :key="index"
                  class="condition-item"
                >
                  <el-input
                    v-model="condition.condition"
                    placeholder="条件表达式，如: {{experiment.status}} == 'completed'"
                    style="margin-bottom: 8px"
                  />
                  <el-input
                    v-model="condition.goto"
                    placeholder="目标节点ID"
                    style="margin-bottom: 8px"
                  />
                  <el-button
                    size="small"
                    type="danger"
                    text
                    @click="removeCondition(index)"
                  >
                    删除条件
                  </el-button>
                </div>
                <el-button
                  size="small"
                  @click="addCondition"
                  style="width: 100%"
                >
                  添加条件
                </el-button>
              </div>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>
    <div class="panel-footer" v-if="selectedNode">
      <el-button type="primary" @click="handleSaveConfig" style="width: 100%">
        保存配置
      </el-button>
    </div>

    <!-- 配置编辑器对话框 -->
    <ConfigEditorDialog
      v-model="configEditorVisible"
      :node-config="nodeConfig.config"
      :node-name="nodeConfig.label || '未命名节点'"
      :predecessor-nodes="availablePredecessorNodes"
      @confirm="handleConfigConfirm"
    />

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { getNodeConfig } from './nodeTypes'
import { useTemplateStore } from '@/stores/template'
import ConfigEditorDialog from './ConfigEditorDialog.vue'

const props = defineProps({
  selectedNode: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update-node', 'delete-node'])

const templateStore = useTemplateStore()

// 从父组件注入工作流数据
const workflowData = inject('workflowData', ref({ nodes: [], edges: [] }))

// 配置编辑器对话框状态
const configEditorVisible = ref(false)

const nodeConfig = ref({
  label: '',
  config: {}
})

// 实验模板选项
const templateOptions = computed(() => {
  return templateStore.templates.map(template => ({
    label: `${template.name} (ID: ${template.id})`,
    value: template.id
  }))
})

const nodeTypeConfig = computed(() => {
  if (!props.selectedNode) return null
  return getNodeConfig(props.selectedNode.type)
})

const nodeTypeLabel = computed(() => {
  return nodeTypeConfig.value?.label || ''
})

const configFields = computed(() => {
  return nodeTypeConfig.value?.configFields || []
})

// 获取字段的选项列表（支持动态选项）
const getFieldOptions = (field) => {
  // 如果字段是 template_id，返回动态加载的模板选项
  if (field.key === 'template_id') {
    return templateOptions.value
  }
  // 否则返回字段自带的选项
  return field.options || []
}

// 计算可引用的前置节点（用于 ConfigEditorDialog）
const availablePredecessorNodes = computed(() => {
  if (!props.selectedNode || !workflowData.value.nodes || !workflowData.value.edges) {
    return []
  }

  const currentNodeId = props.selectedNode.id
  const predecessorIds = new Set()

  // 构建依赖图：找到所有能到达当前节点的前置节点
  const findPredecessors = (nodeId, visited = new Set()) => {
    if (visited.has(nodeId)) return
    visited.add(nodeId)

    workflowData.value.edges.forEach(edge => {
      if (edge.target === nodeId && edge.source !== currentNodeId) {
        predecessorIds.add(edge.source)
        findPredecessors(edge.source, visited)
      }
    })
  }

  findPredecessors(currentNodeId)

  // 返回前置节点的详细信息（包含完整配置）
  return workflowData.value.nodes
    .filter(node => predecessorIds.has(node.id))
    .map(node => ({
      id: node.id,
      label: node.data?.label || node.type,
      type: node.type,
      config: node.data?.config || {} // 添加完整配置信息
    }))
})

// 打开配置编辑器
const openConfigEditor = () => {
  if (!nodeConfig.value.config.template_id) {
    ElMessage.warning('请先选择实验模板')
    return
  }
  configEditorVisible.value = true
}

// 处理配置确认
const handleConfigConfirm = (yamlConfig) => {
  // 保存完整配置到节点
  nodeConfig.value.config.experimentConfig = yamlConfig
  console.log('实验配置已保存:', yamlConfig.substring(0, 100))
}

// 预览配置
const previewConfig = () => {
  if (!nodeConfig.value.config.experimentConfig) return

  ElMessageBox.alert(
    `<pre style="max-height: 500px; overflow: auto;">${nodeConfig.value.config.experimentConfig}</pre>`,
    '实验配置预览',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  )
}

// 监听选中节点变化
watch(
  () => props.selectedNode,
  (newNode) => {
    if (newNode) {
      // 确保 config 是对象类型,防止数组被展开成数字键对象
      const nodeConfigData = newNode.data.config
      let safeConfig = {}

      if (nodeConfigData && typeof nodeConfigData === 'object' && !Array.isArray(nodeConfigData)) {
        safeConfig = { ...nodeConfigData }
      } else if (nodeConfigData && typeof nodeConfigData === 'object') {
        // 如果是数组或其他类型,尝试转换为对象
        console.warn('Node config is not a plain object, resetting to default', nodeConfigData)
        safeConfig = {}
      }

      nodeConfig.value = {
        label: newNode.data.label || '',
        config: safeConfig
      }
    }
  },
  { immediate: true, deep: true }
)

const handleSaveConfig = async () => {
  if (!props.selectedNode) return

  // 确保 config 是对象类型
  let safeConfig = {}
  if (nodeConfig.value.config && typeof nodeConfig.value.config === 'object' && !Array.isArray(nodeConfig.value.config)) {
    // 如果未配置 experimentConfig 且选择了模板，则自动填充模板的默认配置
    if (!nodeConfig.value.config.experimentConfig && nodeConfig.value.config.template_id) {
      try {
        const template = await templateStore.getTemplateById(nodeConfig.value.config.template_id)
        if (template && template.yaml_content) {
          nodeConfig.value.config.experimentConfig = template.yaml_content
          console.log('已自动填充模板默认配置')
        }
      } catch (error) {
        console.error('获取模板配置失败:', error)
        ElMessage.warning('获取模板默认配置失败，请手动配置')
      }
    }
    safeConfig = { ...nodeConfig.value.config }
  } else {
    console.warn('Invalid config type when saving, using empty object')
  }

  emit('update-node', {
    id: props.selectedNode.id,
    data: {
      ...props.selectedNode.data,
      label: nodeConfig.value.label,
      config: safeConfig
    }
  })

  ElMessage.success('节点配置已保存')
}

const handleDeleteNode = () => {
  if (!props.selectedNode) return
  emit('delete-node', props.selectedNode.id)
}

const addCondition = () => {
  if (!nodeConfig.value.config.conditions) {
    nodeConfig.value.config.conditions = []
  }
  nodeConfig.value.config.conditions.push({
    condition: '',
    goto: ''
  })
}

const removeCondition = (index) => {
  nodeConfig.value.config.conditions.splice(index, 1)
}

// 组件挂载时加载实验模板列表
onMounted(async () => {
  try {
    await templateStore.fetchTemplates({ page: 1, page_size: 100 })
  } catch (error) {
    console.error('加载实验模板列表失败:', error)
  }
})
</script>

<style lang="scss" scoped>
.property-panel {
  width: 320px;
  height: 100%;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;

  .panel-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .panel-body {
    flex: 1;
    padding: 16px;
    overflow-y: auto;

    .node-config {
      .conditions-config {
        .condition-item {
          padding: 12px;
          margin-bottom: 12px;
          background: #f5f7fa;
          border-radius: 4px;
        }
      }
    }
  }

  .panel-footer {
    padding: 16px;
    border-top: 1px solid #e4e7ed;
  }
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.field-hint {
  margin-top: 4px;
  font-size: 12px;
}

.config-editor-section {
  display: flex;
  flex-direction: column;
  gap: 8px;

  .config-status {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}
</style>
